package org.fin.session.statement;

import org.fin.exception.NoSuchTypeException;
import org.fin.exception.PersistenceFrameworkException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultSetHandler {

  private final Class<?> resultTypeCls;

  private final ResultSet resultSet;

  public ResultSetHandler(String resultType, ResultSet resultSet) {
    try {
      this.resultTypeCls = Class.forName(resultType);
    } catch (ClassNotFoundException e) {
      throw new NoSuchTypeException("找不到对应的结果类型: " + resultType, e);
    }

    this.resultSet = resultSet;
  }




  public List<Object> handle() throws SQLException {


    ArrayList<Object> results = new ArrayList<>();
    while (resultSet.next()) {


      Object resultObject = null;
      try {
        resultObject = resultTypeCls.newInstance();
      } catch (Exception e) {
        throw new PersistenceFrameworkException("结果对象初始化失败: ", e);
      }


      ResultSetMetaData metaData = resultSet.getMetaData();
      for (int i = 1; i <= metaData.getColumnCount(); i++) {
        // 字段名
        String columnName = metaData.getColumnName(i);
        // 字段值
        Object columnValue = resultSet.getObject(columnName);

        // 使用反射或者内省，根据数据库表和实体的对应关系，完成封装
        PropertyDescriptor descriptor = null;
        try {

          descriptor = new PropertyDescriptor(columnName, resultTypeCls);
          Method method = descriptor.getWriteMethod();
          method.invoke(resultObject, columnValue);

        } catch (Exception e) {
          throw new PersistenceFrameworkException("结果对象初始化失败: ", e);
        }
      }
      results.add(resultObject);
    }

    return results;
  }

}
